<template>
  <div class="container fade-in">
    <div class="header">
      <h2 class="section-title">优惠券管理</h2>
      <div class="actions">
        <router-link to="/coupons/edit" class="btn primary">
          <span class="icon" v-html="'➕'"></span>
          创建优惠券模板
        </router-link>
      </div>
    </div>

    <!-- 统计卡片 -->
    <div class="grid kpi">
      <div class="card kpi slide-up" style="animation-delay: 0.1s">
        <div class="icon" style="background: var(--primary)" v-html="'📊'"></div>
        <div class="meta">
          <div class="label">模板总数</div>
          <div class="value">{{ couponStats.templateCount }}</div>
        </div>
      </div>
      <div class="card kpi slide-up" style="animation-delay: 0.2s">
        <div class="icon" style="background: var(--success)" v-html="'📤'"></div>
        <div class="meta">
          <div class="label">已发放</div>
          <div class="value">{{ couponStats.issuedCount }}</div>
        </div>
      </div>
      <div class="card kpi slide-up" style="animation-delay: 0.3s">
        <div class="icon" style="background: var(--info)" v-html="'✅'"></div>
        <div class="meta">
          <div class="label">已使用</div>
          <div class="value">{{ couponStats.usedCount }}</div>
        </div>
      </div>
      <div class="card kpi slide-up" style="animation-delay: 0.4s">
        <div class="icon" style="background: var(--warning)" v-html="'💰'"></div>
        <div class="meta">
          <div class="label">总优惠金额</div>
          <div class="value">¥{{ (couponStats.totalDiscount / 100).toFixed(2) }}</div>
        </div>
      </div>
    </div>

    <!-- 筛选器 -->
    <div class="card filters slide-up" style="animation-delay: 0.5s">
      <CouponFilters
        @filter-change="handleFilterChange"
        @reset="handleResetFilters"
      />
    </div>

    <!-- 数据表格 -->
    <div class="card slide-up" style="animation-delay: 0.6s">
      <div class="table-header">
        <h3 class="section-title">优惠券模板列表</h3>
        <div class="table-actions">
          <button class="btn secondary sm" @click="loadTemplates">
            <span class="icon" v-html="'🔄'"></span>
            刷新
          </button>
        </div>
      </div>

      <div v-if="tableLoading" class="loading-state">
        <div class="spinner"></div>
        <p>加载中...</p>
      </div>

      <div v-else-if="templates.length === 0" class="empty-state">
        <div class="empty-icon" v-html="'🎫'"></div>
        <h4>暂无优惠券模板</h4>
        <p>还没有创建任何优惠券模板，点击上方按钮创建第一个模板</p>
      </div>

      <div v-else>
        <CouponTable
          :data="templates"
          :loading="tableLoading"
          @refresh="loadTemplates"
          @view="handleView"
          @edit="handleEdit"
          @inventory="handleInventory"
          @delete="handleDelete"
        />
      </div>

      <!-- 分页 -->
      <div v-if="pagination.total.value > 0" class="pagination">
        <button 
          class="btn secondary sm" 
          :disabled="!pagination.hasPrev"
          @click="pagination.prev()"
        >
          上一页
        </button>
        <span class="page-info">
          第 {{ pagination.current }} 页，共 {{ pagination.totalPages }} 页
        </span>
        <button 
          class="btn secondary sm" 
          :disabled="!pagination.hasNext"
          @click="pagination.next()"
        >
          下一页
        </button>
      </div>
    </div>

    <!-- 增加库存弹窗 -->
    <InventoryModal
      v-model="inventoryModalVisible"
      :template="selectedTemplate"
      :loading="inventoryLoading"
      @submit="handleInventorySubmit"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, watch } from 'vue'
import { useRouter } from 'vue-router'
import { useAuthStore } from '@/stores/auth'
import { BaseButton } from '@/components/common'
import { CouponStats, CouponFilters, CouponTable, InventoryModal } from '@/components/coupon'
import { CouponService, type CouponTemplate, type CouponTemplateQueryRequest } from '@/services/coupon'
import { usePagination, useModal } from '@/composables'

// 路由
const router = useRouter()
const authStore = useAuthStore()

// 状态管理
const statsLoading = ref(false)
const tableLoading = ref(false)
const inventoryLoading = ref(false)

const templates = ref<CouponTemplate[]>([])
const selectedTemplate = ref<CouponTemplate | null>(null)

const couponStats = reactive({
  templateCount: 0,
  issuedCount: 0,
  usedCount: 0,
  totalDiscount: 0
})

const filters = reactive<CouponTemplateQueryRequest>({
  name: '',
  couponType: undefined,
  isActive: undefined,
  pageIndex: 1,
  pageSize: 10
})

// 分页
const pagination = usePagination({
  pageSize: filters.pageSize,
  total: 0
})

// 模态框
const { visible: inventoryModalVisible, open: openInventoryModal, close: closeInventoryModal } = useModal()

// 生命周期
onMounted(() => {
  loadStatistics()
  loadTemplates()
})

// 监听分页变化
watch([pagination.current, pagination.size], () => {
  loadTemplates()
})

// 方法
async function loadStatistics() {
  statsLoading.value = true
  try {
    const result = await CouponService.getStatistics()
    if (result.code === 0 && result.data) {
      couponStats.templateCount = result.data.totalTemplates || 0
      couponStats.issuedCount = result.data.totalIssued || 0
      couponStats.usedCount = result.data.totalUsed || 0
      couponStats.totalDiscount = result.data.totalDiscountAmount || 0
    }
  } catch (error) {
    console.error('加载统计数据失败:', error)
  } finally {
    statsLoading.value = false
  }
}

async function loadTemplates() {
  tableLoading.value = true
  try {
    const params = {
      ...filters,
      pageIndex: pagination.current.value,
      pageSize: pagination.size.value
    }
    
    const result = await CouponService.getTemplateList(params)
    if (result.code === 0 && result.data) {
      templates.value = result.data.data
      pagination.total.value = result.data.total
    } else {
      templates.value = []
      pagination.total.value = 0
    }
  } catch (error: any) {
    console.error('加载优惠券模板失败:', error)
    
    // 处理401错误
    if (error?.message?.includes('401') || error?.message?.includes('Unauthorized')) {
      authStore.logout()
      router.push('/login')
      return
    }
    
    templates.value = []
    pagination.total.value = 0
  } finally {
    tableLoading.value = false
  }
}

function handleFilterChange(newFilters: any) {
  Object.assign(filters, newFilters)
  pagination.current.value = 1 // 重置到第一页
  loadTemplates()
}

function handleResetFilters() {
  Object.assign(filters, {
    name: '',
    couponType: undefined,
    isActive: undefined
  })
  pagination.current.value = 1
  loadTemplates()
}

function handleCreate() {
  router.push('/coupons/edit')
}

function handleView(item: CouponTemplate) {
  router.push(`/coupons/detail/${item.id}`)
}

function handleEdit(item: CouponTemplate) {
  router.push(`/coupons/edit/${item.id}`)
}

function handleInventory(item: CouponTemplate) {
  selectedTemplate.value = item
  openInventoryModal()
}

async function handleDelete(item: CouponTemplate) {
  if (!confirm(`确定要删除优惠券模板"${item.name}"吗？此操作不可恢复。`)) {
    return
  }
  
  try {
    const result = await CouponService.deleteTemplate(item.id!)
    if (result.code === 0) {
      alert('删除成功')
      loadTemplates()
    } else {
      alert('删除失败：' + result.message)
    }
  } catch (error) {
    console.error('删除模板出错:', error)
    alert('删除失败，请稍后重试')
  }
}

async function handleInventorySubmit(amount: number) {
  if (!selectedTemplate.value) return
  
  inventoryLoading.value = true
  try {
    const result = await CouponService.increaseInventory(
      selectedTemplate.value.id!,
      amount
    )
    
    if (result.code === 0) {
      alert('库存增加成功')
      closeInventoryModal()
      loadTemplates()
    } else {
      alert('库存增加失败：' + result.message)
    }
  } catch (error) {
    console.error('增加库存出错:', error)
    alert('库存增加失败，请稍后重试')
  } finally {
    inventoryLoading.value = false
  }
}
</script>

<style scoped>
.container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
}

.section-title {
  font-size: 24px;
  font-weight: 600;
  color: var(--text-primary);
  margin: 0;
}

.actions {
  display: flex;
  gap: 12px;
}

.btn {
  display: inline-flex;
  align-items: center;
  gap: 8px;
  padding: 8px 16px;
  border: none;
  border-radius: 6px;
  font-size: 14px;
  font-weight: 500;
  text-decoration: none;
  cursor: pointer;
  transition: all 0.2s ease;
}

.btn.primary {
  background: var(--primary);
  color: white;
}

.btn.primary:hover {
  background: var(--primary-dark);
}

.btn.secondary {
  background: var(--bg-secondary);
  color: var(--text-primary);
  border: 1px solid var(--border);
}

.btn.secondary:hover {
  background: var(--bg-tertiary);
}

.btn.sm {
  padding: 6px 12px;
  font-size: 12px;
}

.btn:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

.grid.kpi {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(240px, 1fr));
  gap: 20px;
  margin-bottom: 24px;
}

.card {
  background: white;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  border: 1px solid var(--border);
}

.card.kpi {
  display: flex;
  align-items: center;
  gap: 16px;
  padding: 16px 20px;
}

.card.kpi .icon {
  width: 48px;
  height: 48px;
  border-radius: 8px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 20px;
  color: white;
}

.card.kpi .meta .label {
  font-size: 14px;
  color: var(--text-secondary);
  margin-bottom: 4px;
}

.card.kpi .meta .value {
  font-size: 24px;
  font-weight: 600;
  color: var(--text-primary);
}

.filters {
  margin-bottom: 24px;
}

.table-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.table-header .section-title {
  font-size: 18px;
}

.table-actions {
  display: flex;
  gap: 8px;
}

.loading-state, .empty-state {
  text-align: center;
  padding: 60px 20px;
  color: var(--text-secondary);
}

.spinner {
  width: 32px;
  height: 32px;
  border: 3px solid var(--border);
  border-top: 3px solid var(--primary);
  border-radius: 50%;
  animation: spin 1s linear infinite;
  margin: 0 auto 16px;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

.empty-icon {
  font-size: 48px;
  margin-bottom: 16px;
}

.pagination {
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 16px;
  margin-top: 24px;
}

.page-info {
  font-size: 14px;
  color: var(--text-secondary);
}

/* 动画效果 */
.fade-in {
  animation: fadeIn 0.3s ease-out;
}

.slide-up {
  animation: slideUp 0.4s ease-out;
}

@keyframes fadeIn {
  from {
    opacity: 0;
  }
  to {
    opacity: 1;
  }
}

@keyframes slideUp {
  from {
    opacity: 0;
    transform: translateY(20px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

/* 响应式设计 */
@media (max-width: 768px) {
  .container {
    padding: 16px;
  }
  
  .header {
    flex-direction: column;
    gap: 16px;
    align-items: stretch;
  }
  
  .grid.kpi {
    grid-template-columns: 1fr;
  }
  
  .pagination {
    flex-direction: column;
    gap: 8px;
  }
}
</style>